package GDoc::Logger;

use feature ':5.10';

use Moose::Role;
use Scalar::Util 'blessed';

sub get_logger {
    my $self = shift;
    my %args = @_;

    my $jobclass = blessed $self;

    return bless { jobclass => $jobclass }, $self->logger_class;
}

sub logger_class { 
    return 'GDoc::Logger::Writer';
}


package GDoc::Logger::Writer;

use Moose;
use DateTime;

use GDoc::DB;

has 'jobclass'     => ( is       => 'ro',
                        isa      => 'Str',
                        required => 1
                      );

sub _db { 
    state $dbh;

    return $dbh if defined $dbh;
    return $dbh = GDoc::DB->new;
}


foreach my $level( qw{trace info warn error fatal} ) { 
    my $meth = sub { 
        my $self = shift;
        my $msg = shift;

        my $entry = $self->_db->logs->new( {
            class    => $self->jobclass,
            proc     => $$,
            level    => $level,
            message  => $msg,
            date     => DateTime->now
        } );

        $entry->insert;
    };

    no strict 'refs';
    *{ $level } = $meth;
}



1;

